package com.lp.common.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.lp.common.annotation.ExcelColumn;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-09-21 22:09:04
 */
public class ExcelUtils {

    public static void writeExcel(HttpServletResponse response, String fileName, String sheetName, List<?> dataList,
                                  Class<?> entityClass) {
        List<Field> fields = new ArrayList<>();
        for (Field field : entityClass.getDeclaredFields()) {
            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
            if (annotation != null) {
                fields.add(field);
            }
        }
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet(sheetName);
            // 设置表头样式
            CellStyle headerCellStyle = workbook.createCellStyle();
            // 设置背景色为浅绿色
            headerCellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
            // 设置填充模式
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = workbook.createFont();
            // 设置字体加粗
            font.setBold(true);
            headerCellStyle.setFont(font);
            // 创建表头行
            Row headerRow = sheet.createRow(0);
            for (Field field : fields) {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                Cell headerCell = headerRow.createCell(annotation.index());
                headerCell.setCellValue(annotation.head());
                headerCell.setCellStyle(headerCellStyle);
            }

            // 填充数据行
            int rowNum = 1;
            for (Object data : dataList) {
                Row row = sheet.createRow(rowNum++);
                for (Field field : fields) {
                    field.setAccessible(true);
                    ExcelColumn ann = field.getAnnotation(ExcelColumn.class);
                    Cell cell = row.createCell(ann.index());
                    Object value = field.get(data);
                    cell.setCellValue(value == null ? null : value.toString());
                }
            }
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", String.format("attachment; filename=%s.xlsx", fileName));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
